<template>
  <div>
    <h3>
      Use 'for (index in array) {}' in computed or methods. When the array is initialized to empty, adding array items cannot refresh the
      view
    </h3>
    <button @click="addItem">add item</button> <button @click="removeItem">remove item</button>
    <fieldset>
      <legend>expected : array item grouping rendering</legend>
      <div v-for="(group, i) in expected" :key="i">
        group: {{ i }}
        <div>{{ group }}</div>
      </div>
    </fieldset>
    <fieldset>
      <legend>expected actually happening : The view cannot be refreshed</legend>
      <div v-for="(group, i) in groups" :key="i">
        group: {{ i }}
        <div>{{ group }}</div>
      </div>
    </fieldset>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [],
      obj: {}
    };
  },
  computed: {
    groups() {
      /**
       *  Use 'for (index in array) {}' in computed or methods.
       *  When the array is initialized to empty, adding array items cannot refresh the view
       */
      let list = this.list || [];
      let groups = {};
      for (const i in list) {
        let item = list[i];
        let groupName = item.group;
        groups[groupName] = groups[groupName] || [];
        groups[groupName].push(item);
      }
      return groups;
      // return list.length && groups; //but comment code work right
    },

    expected() {
      //this code work right too
      let list = this.list || [];
      let groups = {};
      for (const item of list) {
        let groupName = item.group;
        groups[groupName] = groups[groupName] || [];
        groups[groupName].push(item);
      }
      return groups;
    }
  },
  methods: {
    addItem() {
      let item = { group: Math.floor(Math.random() * 3) };
      this.list.push(item);
      this.obj = {};
      for (const i in this.list) {
        this.obj[i] = this.list[i];
      }
    },
    removeItem() {
      this.list.splice(0, 1);
    }
  }
};
</script>
